package com.lazyking.nio.work1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class NioClient {
    public static void main(final String[] args) throws IOException {

        //1.创建客户端socket通道
        SocketChannel socketChannel = SocketChannel.open();
        //2.连接服务器
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        //3.非阻塞模式 设置缓冲区大小
        socketChannel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //4.发送数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("input: ");

        while (true){
            String msg = scanner.nextLine();
            if (msg.equals("exit")){
                break;
            }
            buffer.put(msg.getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        socketChannel.close();

    }
}
